import { asyncRouterMap, constantRouterMap } from '@/router'

/**
 * 通过resourceIdList判断是否与当前用户权限匹配
 * @param resourceIdList
 * @param route
 */
function hasPermission(resourceIdList, route) {
  if(route.meta && route.meta.permission === 'all'){
    return true
  } else if(resourceIdList.includes(route.name)){
    return true
  } else if(route.children){
    return route.children.some(i => hasPermission(resourceIdList, i))
  } else {
    return false
  }
}

function formatKey(word){
  if(word){
    return word.charAt(0).toUpperCase() + word.slice(1)
  }
  return ''
}
/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param resourceIdList
 */
function filterAsyncRouter(asyncRouterMap, resourceIdList) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if(route.path){
      if(hasPermission(resourceIdList, route)){
        // console.log(route, 11144)
        if (route.children && route.children.length) {
          route.children = filterAsyncRouter(route.children, resourceIdList)
        } else if(route.meta && route.meta.buttons){
          for(let key in route.meta.buttons){
            route.meta.buttons[key].enabled = resourceIdList.includes(`${route.name}${formatKey(key)}`)
          }
        }
        return true
      }
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { isAdmin, resourceIdList } = data
        let accessedRouters
        if (isAdmin) {
          accessedRouters = asyncRouterMap
        } else {
          accessedRouters = filterAsyncRouter(asyncRouterMap, resourceIdList)
          let firstRouter = asyncRouterMap[0]
          
          let router = accessedRouters[0]
          while(router.children && router.children[0] && router.children[0].path && router.children[0].path[0] === '/'){
            router = router.children[0]
          }
          firstRouter.redirect = router.path + '/' + router.children[0].path
          accessedRouters = [firstRouter].concat(accessedRouters)
          accessedRouters = accessedRouters.concat([{ path: "*", redirect: "/404", hidden: true }])
        }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
